#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

//    this->resize(QSize(639,459));

    open_flag = 0;     //串口关
    close_flag = 0;     //灯开
    value = 11;
    timer.start(1000);
//    timer2.start(500);
    connect(&timer, SIGNAL(timeout()), this, SLOT(timerOut_slot()));
    connect(&timer2, SIGNAL(timeout()), this, SLOT(foreach1()));
    connect(&timer3, SIGNAL(timeout()), this, SLOT(output()));
    connect(&serial, SIGNAL(readyRead()), this, SLOT(read_serial_slot()));


}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::timerOut_slot(void)
{
    QStringList serial_Name_temp_list;

    if(open_flag == 1)
        return;

    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        serial_Name_temp_list << info.portName();
    }

    if(serial_Name_temp_list != serial_Name_list)
    {
        ui->serial_number_comboBox->clear();
        serial_Name_list = serial_Name_temp_list;
        ui->serial_number_comboBox->addItems(serial_Name_list);
    }
}

void MainWindow::on_serial_open_pushButton_clicked()
{
    if(open_flag == 0)
    {
        serial.setPortName(ui->serial_number_comboBox->currentText());
        serial.setBaudRate(ui->baud_rate_comboBox->currentText().toInt());
        switch(ui->parity_bit_comboBox->currentIndex())
        {
            case 0:
                serial.setParity(QSerialPort::NoParity); break;
            case 1:
                serial.setParity(QSerialPort::OddParity); break;
            case 2:
                serial.setParity(QSerialPort::EvenParity); break;
            case 3:
                serial.setParity(QSerialPort::MarkParity); break;
            case 4:
                serial.setParity(QSerialPort::SpaceParity); break;
            default:
                break;
        }
        switch(ui->data_bit_comboBox->currentIndex())
        {
//            case  0:
//                serial.setDataBits(QSerialPort::Data5); break;
//            case  1:
//                serial.setDataBits(QSerialPort::Data6); break;
//            case  2:
//                serial.setDataBits(QSerialPort::Data7); break;
            case  0:
                serial.setDataBits(QSerialPort::Data8); break;
            default:
                break;
        }
        switch(ui->stop_bit_comboBox->currentIndex())
        {
        case  0:
            serial.setStopBits(QSerialPort::OneStop); break;
        case  1:
            serial.setStopBits(QSerialPort::OneAndHalfStop); break;
        case  2:
            serial.setStopBits(QSerialPort::TwoStop); break;
        default:
            break;
        }
        serial.setFlowControl(QSerialPort::NoFlowControl);
        if(serial.open(QIODevice::ReadWrite) == true)
        {
            open_flag = 1;
            ui->serial_open_pushButton->setText(QString("关闭"));
            qDebug()<<"open success";
        }
        else
        {
            QMessageBox::warning(NULL, "warning", "串口不存在或者被其它应用程序占用！", "确定");
            qDebug()<<"open failed";
        }

    }
    else
    {
        serial.close();
        ui->serial_open_pushButton->setText(QString("打开"));
        open_flag = 0;
        qDebug()<<"close success";
    }
}


/* 串口写入函数 */
void MainWindow::serial_write(unsigned char *buf, int len)
{
    /* 包标识 */
//    buf[5] = 0x00;

    /* ID 20171219+ */
//    buf[7] = ui->spinBox->value();

    printf("write_serial_%d[", len);
    for(int i = 0; i < len; i++)
        printf("%.2x ", buf[i]);
    printf("]\n");

//    std::cout.flush();
    serial.write((const char *)buf, len);
}

/* 接收串口信号 */
void MainWindow::read_serial_slot(void)
{

    QByteArray temp;
    char *rx_data;
    int len;
//sleep(5);
    temp = serial.readAll();

    if(!temp.isEmpty())
    {
        read_array.append(temp);
        if(!read_array.contains(0x0D))
            return;
        if(!read_array.contains(0x0A))
            return;

    }

    rx_data = read_array.data();
    len = read_array.size();

    /* 显示 */
//    QString str = ui->recvTextBrowser->toPlainText();
//    str+=tr(read_array);
//    ui->recvTextBrowser->clear();
//    ui->recvTextBrowser->append(str);

    QDataStream out(&read_array,QIODevice::ReadWrite);    //将字节数组读入
    while(!out.atEnd())
    {
        qint8 outChar = 0;
        out>>outChar;   //每字节填充一次，直到结束
        //十六进制的转换
        QString str = QString("%1").arg(outChar&0xFF,2,16,QLatin1Char('0'));
        ui->recvTextBrowser->insertPlainText(str);
        ui->recvTextBrowser->insertPlainText(" ");
    }
    ui->recvTextBrowser->insertPlainText("\n");
    /* 光标沉底 */
    ui->recvTextBrowser->moveCursor(QTextCursor::End);


    if(rx_data[len - 1] != 0x0a)
    {
        memcpy(wanzheng, rx_data, len);
        fflag = len;
        return;
    }
    else if(fflag != 0)
    {
        memcpy(wanzheng + fflag, rx_data, len);
        rx_data = wanzheng;
        len = fflag + len;
        fflag = 0;
    }

    printf("len = %d\n  [", len);
    for(int i = 0; i < len; i++)
      printf("%.2x ", (uint8_t)rx_data[i]);
    printf("]\n");

printf("rx_data[4] = %x\n", rx_data[4]&0xff);
printf("rx_data[5] = %x\n", rx_data[5]&0xff);
printf("rx_data[6] = %x\n", rx_data[6]&0xff);

printf("rx_data[4] = %x\n", 0xAA);
char aa = 0xaa;
char bb = 0xbb;
char cc = 0xcc;
char dd = 0xdd;
char ee = 0xee;
    switch(rx_data[4])
    {

        case 01:    if(rx_data[5] & 0x01)
                        ui->checkBox_3->setChecked(true);
                    else
                        ui->checkBox_3->setChecked(false);


                    if(rx_data[5] & 0x01 << 1)
                        ui->checkBox_4->setChecked(true);
                    else
                        ui->checkBox_4->setChecked(false);


                    if(rx_data[5] & 0x01 << 2)
                        ui->checkBox_5->setChecked(true);
                    else
                        ui->checkBox_5->setChecked(false);



                    if(rx_data[5] & 0x01 << 3)
                        ui->checkBox->setChecked(true);
                    else
                        ui->checkBox->setChecked(false);


                    if(rx_data[5] & 0x01 << 4)
                        ui->checkBox_2->setChecked(true);
                    else
                        ui->checkBox_2->setChecked(false);
                    break;

        case 02:    if(rx_data[5] == aa && rx_data[6] == bb)
                        ui->label_2->setText("485 Test OK");
                    else
                        ui->label_2->setText("485 Test ERR");
                    break;
        case 03:
                    if(rx_data[5] == cc && rx_data[6] == dd && rx_data[7] == ee)
                        ui->label_5->setText("Lora Test OK");
                    else
                        ui->label_5->setText("Lora Test ERR");
                    break;

        case 04:
                    int timeT = *(uint32_t*)&rx_data[5];   //将当前时间转为时间戳
                    QDateTime time = QDateTime::fromTime_t(timeT);
                    ui->label_4->setText(time.toString("yyyy-MM-dd hh:mm:ss"));
                    break;
//                    qDebug() << time;
    }

    /* 时间部分 */
//    if(rx_data[8] <= 1 && rx_data[8] + rx_data[9] >= 0x8)
//    {
//        QString str;
//        str += "20";
//        str += QString("%1").arg(rx_data[10],2,16,QLatin1Char('0'));
//        str += "/";
//        str += QString("%1").arg(rx_data[11],2,16,QLatin1Char('0'));
//        str += "/";
//        str += QString("%1").arg(rx_data[12],2,16,QLatin1Char('0'));
//        str += " 星期";
//        str += QString("%1").arg(rx_data[13],1,16,QLatin1Char('0'));
//        str += " ";
//        str += QString("%1").arg(rx_data[14],2,16,QLatin1Char('0'));
//        str += ":";
//        str += QString("%1").arg(rx_data[15],2,16,QLatin1Char('0'));
//        str += ":";
//        str += QString("%1").arg(rx_data[16],2,16,QLatin1Char('0'));
//        ui->label->setText(str);
//    }
    read_array.clear();
}

void MainWindow::on_pushButton_sand1_clicked()
{
    uint8_t buf1[100] = {0x00};
    /* 提取参数 */
    QString sand_str(ui->lineEdit_sand1->text());
    QString temp;
    int cnt = 0;
    for(int i = 0; ; i++)
    {
            temp = sand_str.left(2);
            if(temp == "")
                break;
            buf1[i] = temp.toInt(0,16);
            sand_str = sand_str.mid(3);
            qDebug() << temp;
            cnt++;
    }
    serial_write(buf1, cnt);
}

/* 测试输入 */
void MainWindow::on_pushButton_clicked()
{
    if(ui->pushButton_2->text() == "停止测试")
    {
        QMessageBox::warning(NULL, "warning", "请先停止输出测试", "确定");
        return;
    }

    if(ui->pushButton->text() == "测试输入")
    {
        timer2.start(100);
        ui->pushButton->setText("停止测试");
    }
    else
    {
        timer2.stop();
        ui->pushButton->setText("测试输入");
    }
}

/* 测试输出 */
void MainWindow::on_pushButton_2_clicked()
{
    if(ui->pushButton->text() == "停止测试")
    {
        QMessageBox::warning(NULL, "warning", "请先停止输入测试", "确定");
        return;
    }

    if(ui->pushButton_2->text() == "测试输出")
    {
        timer3.start(300);
        ui->pushButton_2->setText("停止测试");
    }
    else
    {
        timer3.stop();
        ui->pushButton_2->setText("测试输出");
    }
}



/* 校时 */
void MainWindow::on_pushButton_3_clicked()
{

    uint8_t buf[18] = {0xEA, 0xEB, 0xEE, 0x00, 0x0B, 0x00, 0x02, 0x00, 0x41, 0x18, 0x01, 0x23, 0x02, 0x0, 0x41, 0x00, 0x0D, 0x0A};
    serial_write(buf, 18);

}


/* 轮询输入 */
void MainWindow::foreach1(void)
{
    count++;
    if(count % 10 == 0)
    {
        uint8_t buf[11] = {0xEA, 0xEB, 0xEE, 0x00, 0x04, 0x00, 0x03, 0xAA, 0xBB, 0x0D, 0x0A};
        serial_write(buf, 11);
    }
    else
    {
        uint8_t buf[10] = {0xEA, 0xEB, 0xEE, 0x00, 0x03, 0x00, 0x04, 0xAA, 0x0D, 0x0A};
        serial_write(buf, 10);
    }
}


/* 轮询输出 */
void MainWindow::output(void)
{
    uint8_t buf[11] = {0xEA, 0xEB, 0xEE, 0x00, 0x04, 0x00, 0x05, 0x01, 0xBB, 0x0D, 0x0A};
    count2++;
    if(count2 % 6 == 0)
        buf[6] = 0x05, buf[7] = 0x01;
    if(count2 % 6 == 1)
        buf[6] = 0x05, buf[7] = 0x02;
    if(count2 % 6 == 2)
        buf[6] = 0x05, buf[7] = 0x03;
    if(count2 % 6 == 3)
        buf[6] = 0x06, buf[7] = 0x01;
    if(count2 % 6 == 4)
        buf[6] = 0x06, buf[7] = 0x02;
    if(count2 % 6 == 5)
        buf[6] = 0x06, buf[7] = 0x03;

    serial_write(buf, 11);
}


void MainWindow::on_pushButton_4_clicked()
{
    ui->recvTextBrowser->clear();
}




void MainWindow::on_pushButton_8_clicked()
{
    uint8_t buf[11] = {0xEA, 0xEB, 0xEE, 0x00, 0x04, 0x00, 0x01, 0xAA, 0xBB, 0x0D, 0x0A};
    serial_write(buf, 11);
    delay(200);

    serial_write(buf, 11);
}

void MainWindow::on_pushButton_9_clicked()
{
    uint8_t buf[14] = {0xEA, 0xEB, 0xEE, 0x00, 0x07, 0x00, 0x02, 0x00, 0xf1, 0xCC, 0xDD, 0xEE, 0x0D, 0x0A};
    serial_write(buf, 14);
}


void MainWindow::delay(unsigned int msec)
{
    QTime _Timer = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < _Timer )
    QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

void MainWindow::on_pushButton_5_clicked()
{
    printf("aaaa\n");
    ui->label_2->setText("");
    ui->label_5->setText("");

    ui->checkBox->setChecked(false);
    ui->checkBox_2->setChecked(false);
    ui->checkBox_3->setChecked(false);
    ui->checkBox_4->setChecked(false);
    ui->checkBox_5->setChecked(false);

    ui->label_4->setText("");
}

void MainWindow::on_pushButton_6_clicked()
{
    ui->pushButton_5->click();

    delay(200);
    ui->pushButton_8->click();

    delay(200);
    ui->pushButton_8->click();


    delay(1000);
    ui->pushButton_9->click();


    delay(1500);
    ui->pushButton->click();

    delay(5000);
    ui->pushButton->click();

    delay(1500);
    ui->pushButton_2->click();

    delay(8000);
    ui->pushButton_2->click();

}
